// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { EachDirItemType, getMetadata, getAllFiles, splitTimePeriod, getRandomTimePeriod, ffVideoOne } from '../serveUtils';
import path from 'path';
import { sleep } from '../globalUtils';
const state = { loading: false };
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  if (state.loading) {
    // 自己用，一次一次的处理，没有并发
    res.status(200).send({ msg: '执行中请稍后……', result: [] });
    return;
  }
  const params: ParamsType = paramsToJson(req);
  const vmsg = paramsValid(params);
  if (vmsg) {
    res.status(405).send({ ...vmsg, result: [] });
  } else {
    let arr = getAllFiles(params.inputDir);
    if (params.maxFileNumber > 0) {
      arr = arr.slice(0, params.maxFileNumber);
    }
    if (Array.isArray(params.identifyExtensions) && params.identifyExtensions.length) {
      arr = arr.filter((o) => params.identifyExtensions.includes(o.ext));
    }
    await filesAddMetadata(arr);
    formatFileItems(arr, params);
    console.log('开始剪辑');
    state.loading = true;
    batchFfFiles(arr)
      .then(() => {
        console.log('剪辑完成');
      })
      .catch((err) => {
        console.log('剪辑失败');
        console.log(err);
      })
      .finally(() => {
        state.loading = false;
      });
    res.status(200).send({ msg: 'success', result: arr });
  }
}
interface ParamsType {
  inputDir: string;
  outputDir: string;
  identifyExtensions: string[];
  minOutputDuration: number;
  maxOutputDuration: number;
  minSplitDuration: number;
  maxSplitDuration: number;
  maxFileNumber: number;
  [str: string]: any;
}
let id = 1
async function batchFfFiles(files: EachDirItemType[]) {
  // console.log(files);
  // return;
  for (let i = 0; i < files.length; i++) {
    const item = files[i];
    for (let j = 0; j < item.subsectionArr.length; j++) {
      const time = item.subsectionArr[j];
      const options = {
        inputFile: item.src,
        outputFile: time.toSrc,
        start: time.start,
        duration: time.duration,
      };
      await ffVideoOne(options);
      console.log('==============>',id++)
      console.log(options)
      await sleep(1000)
    }
  }
}
function paramsValid(params: ParamsType) {
  if (!params.inputDir) {
    return { msg: '"outputDir"缺少输入地址' };
  }
  if (!params.outputDir) {
    return { msg: '"outputDir"缺少输出地址' };
  }
  if (!(params.minOutputDuration > 0)) {
    return { msg: '"minOutputDuration"缺少最小剪辑时长' };
  }
  if (!(params.maxOutputDuration > 0)) {
    return { msg: '"maxOutputDuration"缺少最大剪辑时长' };
  }
  if (params.minSplitDuration > 0) {
    if (!(params.minSplitDuration > params.minOutputDuration && params.minSplitDuration > params.maxOutputDuration)) {
      return { msg: '"minSplitDuration"分割时长必须大于裁剪时长' };
    }
  }
  if (params.maxSplitDuration > 0) {
    if (!(params.maxSplitDuration > params.minOutputDuration && params.maxSplitDuration > params.maxOutputDuration)) {
      return { msg: '"maxSplitDuration"分割时长必须大于裁剪时长' };
    }
  }
}
function paramsToJson(req: NextApiRequest) {
  try {
    return JSON.parse(req.body) || {};
  } catch (error) {
    return {};
  }
}

// 文件数据中添加文件信息数据
async function filesAddMetadata(arr: EachDirItemType[]): Promise<EachDirItemType[]> {
  for (let i = 0; i < arr.length; i++) {
    const o = arr[i];
    const metadata = await getMetadata(o.src);
    o.duration = metadata.duration;
    o.size = metadata.size;
  }
  return arr;
}

function formatFileItems(arr: EachDirItemType[], params: ParamsType) {
  const { minOutputDuration, maxOutputDuration, minSplitDuration, maxSplitDuration, outputDir, inputDir } = params;
  const _inputDir = path.parse(inputDir).dir;
  arr.forEach((o) => {
    const duration = parseInt(o.duration) || 0;
    const st = splitTimePeriod(duration, minSplitDuration, maxSplitDuration);
    o.subsectionArr = st
      .map((ar) => getRandomTimePeriod(ar, minOutputDuration, maxOutputDuration))
      .map((ar, i) => {
        return {
          toSrc: path.join(o.dir.replace(_inputDir, outputDir), o.name + '_X_X_' + ((i + 1) + '').padStart(4, '0') + o.ext),
          start: ar[0],
          duration: ar[1] - ar[0],
        };
      });
  });
}
/*
ffprobe -v error -i "D:\学习\跟尤雨溪一起解读Vue3源码【中英字幕】- Vue Mastery\10.Deep Dive- 10 - Creating a Mini Vue(Av796189639,P10).mp4" -show_format
ffmpeg -i "D:\学习\跟尤雨溪一起解读Vue3源码【中英字幕】- Vue Mastery\10.Deep Dive- 10 - Creating a Mini Vue(Av796189639,P10).mp4"
*/